// pages/order/create/index.js
var app = getApp();
var core = app.requirejs('core');
var diyad = app.requirejs('biz/ad');
var $ = app.requirejs('jquery');
const api = require("../../../utils/api.js")
Page(app.sr.page({
  data: {
    coupons: 1,
    indflang: false,
    flang: false,
    submit: false,
    indexxz: -1,
    image_url: 'https://totolestorage.blob.core.chinacloudapi.cn/totoleec/xcx/coupon/'
  },
  onLoad: function (options) {
    // console.log(app.getCache("code"))
    let $this = this // 小程序配置信息
    wx.login({
      success: res => {
        // app.setCache("code", res.code)
        console.log(res)
        $this.setData({
          code: res.code
        })
      }
    })
    this.setData({
      options,
      goodstype: options.goodstype,
      ordertype: options.ordertype,
      mobile: app.getCache('mobile'),
      // code: app.getCache("code")
    })
    $this.initFunction(options);
    // 小程序配置
    app.miniprogram(function (res) {
      $this.setData({
        bindingNodes: res.bindingNodes
      })
      let globalData = app.globalData
      $this.setData({
        globalData: globalData
      })
    })
    //获取机型
    var isIpx = app.getCache('isIpx');
    if (isIpx) {
      $this.setData({
        isIpx: true,
        iphonexnavbar: 'fui-iphonex-navbar',
        paddingb: 'padding-b'
      })
    } else {
      $this.setData({
        isIpx: false,
        iphonexnavbar: '',
        paddingb: ''
      })
    }
    this.gettemplate()

  },
  initFunction: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    let ordertype = options.ordertype
    let $this = this,
      goodslist = [];
    // 获取缓存地址信息
    let address = app.getCache("address")
    $this.setData({
      addressDetail: address,
    });
    // $this.setData({
    //   bargainid: options.bargainid
    // });
    let useropenid = 'sns_wa_' + app.getCache('userinfo_openid')
    let memberId = app.getCache('userinfo_id');
    var apicontent = ordertype == "1" ? api.orders.preTrialOrder() : api.orders.preOrder()
    // var apicontent = api.orders.preOrder()
    var data = {
      // goodsIds: ordertype == "1" ? options.goodsIds : options.goodsId,//付邮试用
      goodsIds: options.goodsIds, //付邮试用
      type: options.type, //请求类型购物车或立即购买
      couponId: options.couponId ? options.couponId : "", //优惠券id
      addressDetail: address.detailInfo, //收货地址
      buyerName: address.userName, //收货姓名
      addressProvince: address.provinceName, //收货省
      addressArea: address.countyName, //收货详细地址
      addressCity: address.cityName, //收货城市
      buyerMobile: address.telNumber, //收货电话
      //type1专有
      cartIds: options.type == 2 ? options.ids : "", //购物车ids
      // type2专有
      optionId: options.type == 1 ? options.optionId : "", //规格id
      goodsId: options.goodsId, //type1商品id
      total: options.type == 1 ? options.total : "", //type1购买数量
      typeOption: options.typeOption, //规格类型
      typeword: options.typeword, //规格值
    }
    core.get(apicontent, {
      ...data,
      memberId
    }, function (list) {

      if (list.code != 1) {
        $this.setData({
          show: true
        })
        wx.showModal({
          title: '提示',
          content: list.message,
          showCancel: false,
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.navigateBack({
                delta: 1,
              })
            }
          }
        })
      } else {


        // if (list.data.cartList.length < 1) {
        //   wx.showModal({
        //     title: '提示',
        //     content: '商品已售罄',
        //     showCancel: false,
        //     success(res) {
        //       if (res.confirm) {
        //         wx.navigateBack({
        //           delta: 1,
        //         })
        //       } else if (res.cancel) {

        //       }
        //     }
        //   })
        // }

        let listitem = {
          cartList: list.data.cartList,
          calcAmount: list.data.calcAmount,
        }
        $this.setData({
          list: listitem,
          show: true,
        })
        // 满减manjianRuleList
        $this.setData({
          manjianRuleList: list.data.manjianRuleList
        })
        // 单品赠送

        if (list.data.shopSingleGiftList.length > 0) {
          let shopSingleGiftList = list.data.shopSingleGiftList
          let singleGiftIds = []
          shopSingleGiftList.forEach(e => {
            e.giftGoodsMapsList.forEach(ele => {
              let singleItem = ele.id + ':' + ele.count
              singleGiftIds.push(singleItem)
            })
          })
          singleGiftIds = singleGiftIds.join(";")
          $this.setData({
            singleGiftIds,
            shopSingleGiftList,
          })
        }
        //验证码赠礼会员旗舰店

        let codeGiftGoodsMapList = []
        $this.setData({
          codeGiftGoodsMapList,
        })
        if (list.data.codeGiftGoodsMapList) {
          let codeGiftGoodsMapList = list.data.codeGiftGoodsMapList
          $this.setData({
            codeGiftGoodsMapList,
          })
        }

        //首赠礼
        if (list.data.firstPurchaseRuleList) {
          let firstPurchaseRuleList = list.data.firstPurchaseRuleList
          let firstPurchaseId = []
          firstPurchaseRuleList.forEach(e => {
            firstPurchaseId.push(e.id)
          })
          firstPurchaseId = firstPurchaseId.join(";")

          $this.setData({
            firstPurchaseId,
            firstPurchaseRuleList,
          })
        }
        // 为满足条件的满赠
        // if (list.data.fullGiftListtwo) {
        //   $this.setData({
        //     fullGiftListtwo: list.data.fullGiftListtwo[0]
        //   })
        // }
        // 选赠礼
        if (list.data.ChoosGiftList) {
          let ChoosGiftId = []
          let ChoosGiftList = list.data.ChoosGiftList
          let temp = []
          ChoosGiftList.forEach(e => {
            let tempitem = {}
            tempitem.titles = e.titles
            tempitem.chosenum = 0
            e.fullGiftRuleList.forEach(ele => {
              if (ele.songAmount > tempitem.chosenum) {
                tempitem.chosenum = ele.songAmount
              }

              tempitem.fullGiftGoodsMapList = ele.fullGiftGoodsMapList
            })
            temp.push(tempitem)
            // ChoosGiftId.push([])
          })
          $this.setData({
            ChoosGiftId,
            ChoosGiftList: temp,
          })
        }
        // 满赠
        if (list.data.fullGiftList) {
          let fullGiftId = []
          let fullGiftList = list.data.fullGiftList
          // let manzengli = []  //满赠礼放一起1
          fullGiftList.forEach(e => {
            let manzengids = []
            let manzengli = []
            e.manzengli = manzengli
            e.fullGiftRuleList.forEach(ele => {
              ele.fullGiftGoodsMapList.forEach(element => {
                manzengids.push(element.id)
                manzengli.push(element) //满赠礼放一起2
              })
            })
            fullGiftId.push(manzengids)
          })
          $this.setData({
            fullGiftId,
            fullGiftList: list.data.fullGiftList,
            // manzengli  //满赠礼放一起3
          })
        }

        // 计算可以勾选的数量
        let chosenum = 0;
        /**启动广告 */
        diyad.get($this, function (res) {

        })
        $this.setData({
          // todo: 给couponIds赋值
          // canusercoupon: list.data.existsCouponIds.existsCoupon,
          // couponIds: list.data.existsCouponIds.couponIds
          // memberCouponList: memberCouponList
        })
        // 获取优惠券
        if (list.data.memberCouponList.length > 0) {
          let memberCouponList = list.data.memberCouponList
          // 处理优惠券展示的条件以及时间
          // if ($this.data.selectId != 100) {
          //   memberCouponList[$this.data.selectId].select = "checked"
          // }
          var couponId = []
          memberCouponList.forEach(e => {
            let rule = e.couponRuleList[0]
            if (rule.conditions == 0 && rule.singleConsumer > 0) {
              // 满额选增
              e.usercondition = "满" + rule.singleConsumer + "元可用"

            } else if (rule.conditions == 0 && rule.singleBatch > 0) {
              //满件选赠
              e.usercondition = "满" + rule.singleBatch + "件可用"
            } else if (rule.conditions == 2) {
              //满额或满件
              e.usercondition = "满" + rule.singleConsumer + "元或" + rule.singleBatch + "件可用"
            } else if (rule.conditions == 1) {
              //满额且满件
              e.usercondition = "满" + rule.singleConsumer + "元且" + rule.singleBatch + "件可用"
            } else if (rule.conditions == 3) {
              //满额且满件
              e.usercondition = "无条件使用"
            }
            e.coupon.expiryBeginTime = $this.timeFun(e.coupon.expiryBeginTime).split(' ')[0]

            e.coupon.expiryEndTime = $this.timeFun(e.coupon.expiryEndTime).split(' ')[0]
            couponId.push(e.couponId)
          })
          let couponIds = couponId.join(',')
          $this.setData({
            canusercoupon: true,
            memberCouponList: memberCouponList,
            couponIds: couponIds
          })
        }
      }
    });
  },

  getCouponList() {
    let that = this
    let $this = this
    let data = {
      couponIds: this.data.couponIds,
      expireStatus: 1,
      current: 1,
      // current: that.data.couponCurrent,
      size: 100,
      memberId: app.getCache('userinfo_id')
    }
    let url = api.markings.existsCouponListByMemberCart()
    core.post(url, {
      ...data
    }, function (res) {
      // console.log(res)
      let memberCouponList = res.data.rows
      // if (that.data.canusercoupon) {
      // 处理优惠券展示的条件以及时间
      // if ($this.data.selectId != 100) {
      //   console.log(222)
      //   memberCouponList[$this.data.selectId].select = "checked"
      // }
      memberCouponList.forEach(e => {

        // if (e.id == $this.data.currentSelectId) {
        //   e.select = "checked"
        // }
        // let rule = e.couponRuleList[0]
        // e.isPicture = e.donUsePic != "" && e.toUsePic != "" && e.expiredPic != ""
        // if (rule.conditions == 0 && rule.singleConsumer > 0) {
        //   // 满额选增
        //   e.usercondition = "满" + rule.singleConsumer + "元可用"

        // } else if (rule.conditions == 0 && rule.singleBatch > 0) {
        //   //满件选赠
        //   e.usercondition = "满" + rule.singleBatch + "件可用"
        // } else if (rule.conditions == 2) {
        //   //满额或满件
        //   e.usercondition = "满" + rule.singleConsumer + "元或" + rule.singleBatch + "件可用"
        // } else if (rule.conditions == 1) {
        //   //满额且满件
        //   e.usercondition = "满" + rule.singleConsumer + "元且" + rule.singleBatch + "件可用"
        // } else if (rule.conditions == 3) {
        //   //满额且满件
        //   e.usercondition = "无条件使用"
        // }
        e.startTime = $this.timeFun(e.startTime).split(' ')[0]
        e.endTime = $this.timeFun(e.endTime).split(' ')[0]
      })
      // }

      that.setData({
        couponLists: memberCouponList,
        couponTotal: res.data.total
      })
      // console.log(that.data.couponLists)
    })
  },

  //打开优惠券
  // openCopons() {
  //   let that = this
  //   that.setData({
  //     couponBox: true,
  //     couponLists: [],
  //     couponCurrent: 1
  //   })
  //   this.getCouponList()

  // },
  //选择优惠券
  xuanzhecoupon(e) {
    let $this = this
    console.log(e)

    let content = e.currentTarget.dataset.content
    let id = e.currentTarget.dataset.idx
    let couponLists = this.data.couponLists
    if (couponLists[id].select == "checked") {
      console.log(couponLists[id].select)
      console.log(1)
      couponLists.forEach(e => {
        e.select = ''
      })
      let options = this.data.options
      options.couponId = ""
      this.setData({
        couponLists,
        checkecoupon: "",
        options,
        selectId: "",
        currentSelectId: '',
        selectCouponName: ''
      })
    } else {
      console.log(111)
      couponLists.forEach(e => {
        e.select = ''
      })
      couponLists[id].select = "checked"
      let ele = couponLists[id].coupon
      let options = this.data.options
      options.couponId = couponLists[id].id
      let currentSelectId = e.currentTarget.dataset.content.id
      this.setData({
        selectCouponName: couponLists[id].couponsName,
        couponLists,
        checkecoupon: content,
        options,
        selectId: id,
        couponType: couponLists[id].type,
        currentSelectId: currentSelectId
      })
    }


  },
  //提交优惠券
  submitcoupon(e) {
    let $this = this
    let options = this.data.options
    this.onLoad(options)
    $this.setData({
      couponBox: false
    })
  },
  /**
   * 原生添加地址
   */
  selectAddress() {
    let $this = this
    wx.chooseAddress({
      success: function (res2) {
        $this.setData({
          addressDetail: {
            userName: res2.userName,
            telNumber: res2.telNumber,
            cityName: res2.cityName,
            countyName: res2.countyName,
            detailInfo: res2.detailInfo,
            nationalCode: res2.nationalCode,
            postalCode: res2.postalCode,
            provinceName: res2.provinceName,
            full_region: res2.provinceName + res2.countyName + res2.detailInfo
          }
        });
        app.setCache('address', $this.data.addressDetail);
        let options = $this.data.options
        $this.initFunction(options);
      },
      fail: (error) => {

        $this.checkAuthorize('scope.address')
      }
    })
  },

  //验证用户是否授权地址
  checkAuthorize(scope) {
    wx.getSetting({
      success: (res) => {
        // console.log(res.authSetting[scope])
        if (!res.authSetting[scope]) {
          wx.showModal({
            title: '用户未授权',
            content: '拒绝授权将不能体验小程序完整功能，点击确定开启授权',
            success: (res) => {
              // console.log(res)
              if (res.confirm) {
                wx.openSetting({})
              }
            }
          })
        }
      }
    })
  },
  //提交
  //获取手机号
  // 获取手机号
  getPhoneNumber: function (e) {
    let $this = this;
    // console.log(e);

    if (e.detail.errMsg !== "getPhoneNumber:ok") {
      return;
    }
    // 检查登录态是否过期
    wx.checkSession({
      success(res) {
        console.log(res)
        let data = {
          code: $this.data.code,
          iv: e.detail.iv,
          encryptedData: e.detail.encryptedData
        }
        $this.memberPhone(data)
      },
      fail(err) {
        // session_key 已经失效，需要重新执行登录流程
        console.log(err)
        wx.login({
          success: res => {
            $this.setData({
              code: res.code
            })
            // app.setCache("code", res.code)

            let data = {
              code: res.code,
              iv: e.detail.iv,
              encryptedData: e.detail.encryptedData
            }
            $this.memberPhone(data)
          }
        })
        wx.showToast({
          title: '获取手机号失败,请重试',
          icon: "none"
        })
      }
    })
  },
  // getPhoneNumber(e) {
  //   let $this = this
  //   console.log(e.detail.errMsg)
  //   console.log(e.detail.iv)
  //   console.log(e.detail.encryptedData)
  //   if (!e.detail.encryptedData) {
  //     return false
  //   }
  //   // if(e.detail.encryptedData){

  //   // }
  //   wx.login({
  //     success: function (ret) {
  //       let data = {
  //         code: ret.code,
  //         iv: e.detail.iv,
  //         encryptedData: e.detail.encryptedData
  //       }
  //       let apicontent = api.members.memberPhone()
  //       core.post(apicontent, {
  //         ...data
  //       }, function (phone_res) {
  //         if (phone_res.code == 1) {
  //           $this.setData({
  //             mobile: phone_res.data
  //           })
  //           app.setCache('mobile', phone_res.data);
  //           wx.showToast({
  //             title: '成功',
  //           })
  //         } else {
  //           wx.showToast({
  //             title: '获取手机号失败,请重试',
  //             icon: "none"
  //           })
  //         }
  //       })
  //     }
  //   })
  // },
  //获取手机号接口
  memberPhone(data) {
    let $this = this
    let apicontent = api.members.memberPhone()
    core.post(apicontent, {
      ...data
    }, function (phone_res) {
      if (phone_res.code == 1) {
        $this.setData({
          mobile: phone_res.data
        })
        app.setCache('mobile', phone_res.data);
        wx.showToast({
          title: '成功',
        })
      } else {
        wx.showToast({
          title: '获取手机号失败,请重试',
          icon: "none"
        })
      }
    })
  },
  // 获取模板消息
  gettemplate() {
    let that = this
    let apicontent = api.orders.gettemplate()
    core.post(apicontent, {
      'scene': 1
    }, function (res) {
      console.log('模板消息', res)
      let titles = []
      let templates = []
      let masgids = []
      if (res.code == 1) {
        if (res.data && res.data.length != 0) {
          res.data.forEach(item => {
            titles.push(item.msgTitle)
            templates.push(item.templateId)
            masgids.push(item.id)
          })
          console.log(templates)
          that.setData({
            titles,
            templates,
            masgids
          })
        }

      }
    })
  },
  submitOrderbefore(e) {
    if (this.data.submit == true) {
      return false
    }
    if (this.data.addressDetail.length < 1) {
      core.alert('地址没有选择!');
      return;
    }
    var that = this;
    console.log('模板调用', that.data.templates)

    if (that.data.templates && that.data.templates.length != 0) {
      console.log('调用')
      wx.requestSubscribeMessage({
        tmplIds: that.data.templates,
        success(res) {
          let titlesNew = ''
          let masgidsNew = ''
          that.data.templates.forEach((item, index) => {
            if (res[item] == 'reject') {
              console.log('订阅拒绝')
            } else if (res[item] == 'accept') {
              titlesNew += that.data.titles[index] + ','
              masgidsNew += that.data.masgids[index] + ','
            }
          })
          console.log(titlesNew, masgidsNew)

          let apicontent = api.orders.subscribe()
          core.post(apicontent, {
            'msgTitles': titlesNew,
            'msgIds': masgidsNew,
            'openid': getApp().getCache("uderInfo").openid
          }, function (res) {
            if (res.code == 1) {
              console.log('订阅回调成功')
            }
          })
        },
        complete(res) {
          that.submit(e)
        }
      })
    } else {
      that.submit(e)
    }

  },
  // 下单
  submit: function (e) {
    var $this = this;
    //验证码礼物
    let codeArr = []
    if ($this.data.codeGiftGoodsMapList.length > 0) {
      for (let item of $this.data.codeGiftGoodsMapList) {
        codeArr.push(item.codeGiftId)
      }
    }
    // let formid = e.detail.formId
    let memberId = app.getCache('userinfo_id');
    // let mobile = app.getCache('mobile');
    let openid = app.getCache("uderInfo").openid
    let codeGiftIds = codeArr.length == 0 ? "" : codeArr.join(",")
    let fullGiftId = $this.data.fullGiftId.join(";")
    let firstPurchaseId = $this.data.firstPurchaseId
    let singleGiftIds = $this.data.singleGiftIds
    let couponId = $this.data.options.couponId
    let options = $this.data.options,
      address = $this.data.addressDetail,
      couponType = $this.data.couponType
    let data = {
      // goodsIds: $this.data.ordertype == "1" ? options.goodsIds : options.goodsId,//太太乐试用商品
      goodsIds: options.goodsIds, //太太乐试用商品
      type: options.type,
      cartIds: options.type == 2 ? options.ids : "",
      optionId: options.type == 1 ? options.optionId : "",
      memberId,
      codeGiftIds,
      total: options.type == 1 ? options.total : "",
      addressDetail: address.detailInfo,
      goodsId: options.goodsId,
      buyerName: address.userName,
      addressProvince: address.provinceName,
      addressArea: address.countyName,
      addressCity: address.cityName,
      buyerMobile: address.telNumber,
      remark: $this.data.remarks,
      fullGiftId,
      firstPurchaseId,
      singleGiftIds,
      // formid,
      page: 'pages/order/detail/index',
      couponId,
      code: options.code,
      couponType,
      ChoosGiftId: $this.data.ChoosGiftId, //选增礼
    }
    $this.setData({
      submit: true
    });
    let apicontent = $this.data.ordertype == 1 ? api.orders.bookTrialOrder() : api.orders.bookOrder()
    // let apicontent = api.orders.bookOrder()
    core.post(apicontent, {
      ...data
    }, function (ret) {
      // let apicontent = api.orders.getsubmitFormId()
      // core.post(apicontent, {
      //   formId: e.detail.formId,
      // }, function (res) {


      // })

      if (ret.message == "下单成功") {
        let order_data = new Date().getTime()
        app.sr.track('custom_order', {
          "order": {
            "order_id": String(ret.data.order.orderNo),
            "order_time": String(order_data),
            "order_status": "give_order",
            "order_amt": ret.data.order.originalPrice,
            "pay_amt": ret.data.order.originalPrice
            // "cancel_time":''
          },
          "sub_orders": [{
            "sub_order_id": String(ret.data.order.orderNo),
            "order_amt": ret.data.order.originalPrice,
            "pay_amt": ret.data.order.originalPrice
          }]
        })
        wx.showToast({
          title: '下单成功',
          icon: 'success',
          duration: 1000
        })
        let apicontent = api.orders.prepay()
        core.post(apicontent, {
          orderId: ret.data.order.id,
          shopId: 1,
          openid,
        }, function (res) {
          if (res.code == 1) {
            setTimeout(() => {
              core.pay(res.data, function (res) {
                if (res.errMsg == "requestPayment:ok") {
                  let order_pay = new Date().getTime()
                  app.sr.track('custom_order', {
                    "order": {
                      "order_id": String(ret.data.order.orderNo),
                      "order_time": String(order_data),
                      "pay_time": String(order_pay),
                      "order_status": "pay",
                      "order_amt": ret.data.order.originalPrice,
                      "pay_amt": ret.data.order.originalPrice
                    },
                    "sub_orders": [{
                      "sub_order_id": String(ret.data.order.orderNo),
                      "order_amt": ret.data.order.originalPrice,
                      "pay_amt": ret.data.order.originalPrice
                    }]
                  })

                  wx.redirectTo({
                    url: '/pages/order/detail/index?id=' + ret.data.order.id
                  });
                } else {
                  wx.redirectTo({
                    url: '/pages/order/detail/index?id=' + ret.data.order.id
                  });
                }
              }, function () {
                $this.setData({
                  submit: false
                });
                wx.redirectTo({
                  url: '/pages/order/detail/index?id=' + ret.data.order.id
                });
              });
            }, 1000)
          } else {
            core.alert(res.message)
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          content: ret.message,
          showCancel: false,
          success(res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1,
              })
            }
          }
        })
      }
    })
  },
  //卖家留言
  remarks(e) {
    this.setData({
      remarks: e.detail.value
    })
  },
  //优惠卷展开事件
  couponschange() {
    this.setData({
      flang: !this.data.flang
    })
    this.getCouponList()
  },
  //没有优惠卷返回事件
  norecoupons() {
    this.setData({
      flang: false
    })
  },
  //有优惠卷确认事件
  arercoupons(e) {
    let options = this.data.options
    this.onLoad(options)
    this.setData({
      flang: false
    })
  },
  //优惠卷选择事件
  couponsclick(e) {
    let id = e.currentTarget.dataset.id
    let couponid = e.currentTarget.dataset.couponid
    if (!this.data.indflang) {
      this.data.options.couponId = couponid
    } else {
      this.data.options.couponId = ''
    }
    this.setData({
      indexxz: id,
      indflang: !this.data.indflang
    })
  },
  //时间格式化
  timeFun(data) {
    //console.log(data)
    var time = new Date(data)
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours() < 10 ? '0' + time.getHours() : time.getHours();
    var mm = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes();
    var s = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds();
    //console.log(y + '-' + m + '-' + d + ' ' + h + ':' + mm + ':' + s)
    return y + '.' + m + '.' + d + ' ' + h + ':' + mm + ':' + s;
  },


}))